{% extends 'base.html' %}
{% load static %}

{% block title %}权限管理 - CFS Web System{% endblock %}

{% block page_type %}permissions{% endblock %}

{% block breadcrumb_items %}
<li class="breadcrumb-item"><a href="{% url 'dashboard:dashboard' %}">仪表板</a></li>
<li class="breadcrumb-item"><a href="{% url 'settings:settings' %}">系统设置</a></li>
<li class="breadcrumb-item active">权限管理</li>
{% endblock %}

{% block content %}
<div class="row">
    <!-- 权限概览 -->
    <div class="col-12 mb-4">
        <div class="row g-3">
            <div class="col-md-3">
                <div class="card bg-primary text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="card-title mb-0">角色数量</h6>
                                <h3 class="mb-0" id="total-roles">0</h3>
                            </div>
                            <i class="fas fa-user-tag fa-2x opacity-75"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="card-title mb-0">权限数量</h6>
                                <h3 class="mb-0" id="total-permissions">0</h3>
                            </div>
                            <i class="fas fa-shield-alt fa-2x opacity-75"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-warning text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="card-title mb-0">自定义角色</h6>
                                <h3 class="mb-0" id="custom-roles">0</h3>
                            </div>
                            <i class="fas fa-cogs fa-2x opacity-75"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-info text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="card-title mb-0">活跃用户</h6>
                                <h3 class="mb-0" id="active-users">0</h3>
                            </div>
                            <i class="fas fa-users fa-2x opacity-75"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 权限管理标签页 -->
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <ul class="nav nav-tabs card-header-tabs" id="permissions-tabs">
                    <li class="nav-item">
                        <a class="nav-link active" id="roles-tab" data-bs-toggle="tab" href="#roles-panel">
                            <i class="fas fa-user-tag me-2"></i>角色管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="permissions-tab" data-bs-toggle="tab" href="#permissions-panel">
                            <i class="fas fa-shield-alt me-2"></i>权限管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" id="matrix-tab" data-bs-toggle="tab" href="#matrix-panel">
                            <i class="fas fa-table me-2"></i>权限矩阵
                        </a>
                    </li>
                </ul>
            </div>
            
            <div class="tab-content">
                <!-- 角色管理面板 -->
                <div class="tab-pane fade show active" id="roles-panel">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h6 class="mb-0">角色列表</h6>
                            <button type="button" class="btn btn-primary" onclick="addRole()">
                                <i class="fas fa-plus"></i> 添加角色
                            </button>
                        </div>
                        
                        <div class="row" id="roles-container">
                            <!-- 角色卡片将动态加载 -->
                        </div>
                    </div>
                </div>
                
                <!-- 权限管理面板 -->
                <div class="tab-pane fade" id="permissions-panel">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h6 class="mb-0">权限列表</h6>
                            <button type="button" class="btn btn-primary" onclick="addPermission()">
                                <i class="fas fa-plus"></i> 添加权限
                            </button>
                        </div>
                        
                        <!-- 权限分类 -->
                        <div class="accordion" id="permissions-accordion">
                            <!-- 权限分类将动态加载 -->
                        </div>
                    </div>
                </div>
                
                <!-- 权限矩阵面板 -->
                <div class="tab-pane fade" id="matrix-panel">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h6 class="mb-0">权限矩阵</h6>
                            <div class="d-flex gap-2">
                                <button type="button" class="btn btn-outline-secondary" onclick="refreshMatrix()">
                                    <i class="fas fa-sync-alt"></i> 刷新
                                </button>
                                <button type="button" class="btn btn-outline-primary" onclick="exportMatrix()">
                                    <i class="fas fa-download"></i> 导出
                                </button>
                            </div>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-bordered table-sm" id="permissions-matrix">
                                <!-- 权限矩阵将动态生成 -->
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加/编辑角色模态框 -->
<div class="modal fade" id="roleModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="roleModalTitle">添加角色</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="role-form">
                <div class="modal-body">
                    <input type="hidden" id="role-id" name="role_id">
                    
                    <div class="row g-3">
                        <!-- 基本信息 -->
                        <div class="col-12">
                            <h6 class="border-bottom pb-2 mb-3">
                                <i class="fas fa-info-circle me-2"></i>基本信息
                            </h6>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">角色名称 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="role-name" name="name" required>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">角色代码 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="role-code" name="code" required>
                            <div class="form-text">用于系统内部标识，只能包含字母、数字和下划线</div>
                        </div>
                        
                        <div class="col-12">
                            <label class="form-label">角色描述</label>
                            <textarea class="form-control" id="role-description" name="description" rows="3" placeholder="描述角色的职责和用途..."></textarea>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">角色级别</label>
                            <select class="form-select" id="role-level" name="level">
                                <option value="1">1 - 最高级别</option>
                                <option value="2">2 - 高级</option>
                                <option value="3">3 - 中级</option>
                                <option value="4">4 - 普通</option>
                                <option value="5" selected>5 - 最低级别</option>
                            </select>
                            <div class="form-text">级别越低，权限越高</div>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">状态</label>
                            <select class="form-select" id="role-status" name="status">
                                <option value="active">启用</option>
                                <option value="inactive">禁用</option>
                            </select>
                        </div>
                        
                        <!-- 权限分配 -->
                        <div class="col-12">
                            <h6 class="border-bottom pb-2 mb-3 mt-3">
                                <i class="fas fa-shield-alt me-2"></i>权限分配
                            </h6>
                        </div>
                        
                        <div class="col-12">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span>选择权限:</span>
                                <div class="btn-group btn-group-sm">
                                    <button type="button" class="btn btn-outline-primary" onclick="selectAllPermissions()">
                                        全选
                                    </button>
                                    <button type="button" class="btn btn-outline-secondary" onclick="clearAllPermissions()">
                                        清空
                                    </button>
                                </div>
                            </div>
                            
                            <div class="border rounded p-3" style="max-height: 300px; overflow-y: auto;">
                                <div id="role-permissions-tree">
                                    <!-- 权限树将动态加载 -->
                                </div>
                            </div>
                        </div>
                        
                        <!-- 其他设置 -->
                        <div class="col-12">
                            <h6 class="border-bottom pb-2 mb-3 mt-3">
                                <i class="fas fa-cog me-2"></i>其他设置
                            </h6>
                        </div>
                        
                        <div class="col-12">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="role-is-default" name="is_default">
                                <label class="form-check-label" for="role-is-default">
                                    默认角色
                                </label>
                                <div class="form-text">新用户注册时自动分配此角色</div>
                            </div>
                        </div>
                        
                        <div class="col-12">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="role-is-system" name="is_system">
                                <label class="form-check-label" for="role-is-system">
                                    系统角色
                                </label>
                                <div class="form-text">系统角色不能被删除</div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> 保存
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 添加/编辑权限模态框 -->
<div class="modal fade" id="permissionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="permissionModalTitle">添加权限</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="permission-form">
                <div class="modal-body">
                    <input type="hidden" id="permission-id" name="permission_id">
                    
                    <div class="mb-3">
                        <label class="form-label">权限名称 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="permission-name" name="name" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">权限代码 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="permission-code" name="code" required>
                        <div class="form-text">用于系统内部标识，格式如: module.action</div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">权限分类</label>
                        <select class="form-select" id="permission-category" name="category">
                            <option value="core">核心功能</option>
                            <option value="file">文件管理</option>
                            <option value="template">模板管理</option>
                            <option value="task">任务管理</option>
                            <option value="analytics">数据分析</option>
                            <option value="settings">系统设置</option>
                            <option value="user">用户管理</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">权限描述</label>
                        <textarea class="form-control" id="permission-description" name="description" rows="3" placeholder="描述权限的作用和范围..."></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">权限级别</label>
                        <select class="form-select" id="permission-level" name="level">
                            <option value="1">1 - 系统级</option>
                            <option value="2">2 - 管理级</option>
                            <option value="3" selected>3 - 操作级</option>
                            <option value="4">4 - 查看级</option>
                        </select>
                    </div>
                    
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" id="permission-is-system" name="is_system">
                        <label class="form-check-label" for="permission-is-system">
                            系统权限
                        </label>
                        <div class="form-text">系统权限不能被删除</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> 保存
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 角色详情模态框 -->
<div class="modal fade" id="roleDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">角色详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="role-detail-content">
                <!-- 角色详情内容将动态加载 -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="editRoleFromDetail()">
                    <i class="fas fa-edit"></i> 编辑
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 全局变量
let currentRoleId = null;
let currentPermissionId = null;
let allPermissions = [];
let allRoles = [];

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializePermissionsPage();
});

// 初始化权限管理页面
function initializePermissionsPage() {
    // 加载统计数据
    loadPermissionStats();
    
    // 加载角色列表
    loadRoles();
    
    // 加载权限列表
    loadPermissions();
    
    // 绑定事件
    bindEvents();
}

// 绑定事件
function bindEvents() {
    // 标签页切换
    document.querySelectorAll('#permissions-tabs a').forEach(tab => {
        tab.addEventListener('shown.bs.tab', function(e) {
            const target = e.target.getAttribute('href');
            if (target === '#matrix-panel') {
                loadPermissionMatrix();
            }
        });
    });
    
    // 表单提交
    document.getElementById('role-form').addEventListener('submit', saveRole);
    document.getElementById('permission-form').addEventListener('submit', savePermission);
    
    // 角色代码自动生成
    document.getElementById('role-name').addEventListener('input', function() {
        const name = this.value;
        const code = name.toLowerCase().replace(/[^a-z0-9]/g, '_').replace(/_+/g, '_');
        document.getElementById('role-code').value = code;
    });
    
    // 权限代码自动生成
    document.getElementById('permission-name').addEventListener('input', function() {
        const name = this.value;
        const category = document.getElementById('permission-category').value;
        const action = name.toLowerCase().replace(/[^a-z0-9]/g, '_').replace(/_+/g, '_');
        document.getElementById('permission-code').value = `${category}.${action}`;
    });
    
    document.getElementById('permission-category').addEventListener('change', function() {
        const name = document.getElementById('permission-name').value;
        if (name) {
            const action = name.toLowerCase().replace(/[^a-z0-9]/g, '_').replace(/_+/g, '_');
            document.getElementById('permission-code').value = `${this.value}.${action}`;
        }
    });
}

// 加载权限统计
function loadPermissionStats() {
    fetch('/settings/ajax/permission-stats/')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            document.getElementById('total-roles').textContent = data.stats.total_roles;
            document.getElementById('total-permissions').textContent = data.stats.total_permissions;
            document.getElementById('custom-roles').textContent = data.stats.custom_roles;
            document.getElementById('active-users').textContent = data.stats.active_users;
        }
    })
    .catch(error => {
        console.error('加载权限统计失败:', error);
    });
}

// 加载角色列表
function loadRoles() {
    fetch('/settings/ajax/roles/')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            allRoles = data.roles;
            renderRoles(data.roles);
        }
    })
    .catch(error => {
        console.error('加载角色列表失败:', error);
    });
}

// 渲染角色列表
function renderRoles(roles) {
    const container = document.getElementById('roles-container');
    
    if (roles.length === 0) {
        container.innerHTML = `
            <div class="col-12">
                <div class="text-center py-4">
                    <i class="fas fa-user-tag fa-3x text-muted mb-3"></i>
                    <p class="text-muted">暂无角色数据</p>
                </div>
            </div>
        `;
        return;
    }
    
    container.innerHTML = roles.map(role => `
        <div class="col-md-6 col-lg-4 mb-3">
            <div class="card h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <h6 class="card-title mb-0">${role.name}</h6>
                        <div class="dropdown">
                            <button class="btn btn-sm btn-outline-secondary" data-bs-toggle="dropdown">
                                <i class="fas fa-ellipsis-v"></i>
                            </button>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item" href="#" onclick="viewRole(${role.id})"><i class="fas fa-eye me-2"></i>查看</a></li>
                                <li><a class="dropdown-item" href="#" onclick="editRole(${role.id})"><i class="fas fa-edit me-2"></i>编辑</a></li>
                                <li><a class="dropdown-item" href="#" onclick="copyRole(${role.id})"><i class="fas fa-copy me-2"></i>复制</a></li>
                                ${!role.is_system ? '<li><hr class="dropdown-divider"></li><li><a class="dropdown-item text-danger" href="#" onclick="deleteRole(' + role.id + ')"><i class="fas fa-trash me-2"></i>删除</a></li>' : ''}
                            </ul>
                        </div>
                    </div>
                    
                    <p class="card-text text-muted small">${role.description || '暂无描述'}</p>
                    
                    <div class="mb-2">
                        <span class="badge bg-${role.status === 'active' ? 'success' : 'secondary'} me-1">
                            ${role.status === 'active' ? '启用' : '禁用'}
                        </span>
                        <span class="badge bg-info me-1">级别 ${role.level}</span>
                        ${role.is_default ? '<span class="badge bg-warning">默认</span>' : ''}
                        ${role.is_system ? '<span class="badge bg-dark">系统</span>' : ''}
                    </div>
                    
                    <div class="d-flex justify-content-between align-items-center">
                        <small class="text-muted">
                            <i class="fas fa-users me-1"></i>${role.user_count} 用户
                        </small>
                        <small class="text-muted">
                            <i class="fas fa-shield-alt me-1"></i>${role.permission_count} 权限
                        </small>
                    </div>
                </div>
            </div>
        </div>
    `).join('');
}

// 加载权限列表
function loadPermissions() {
    fetch('/settings/ajax/permissions/')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            allPermissions = data.permissions;
            renderPermissions(data.permissions);
        }
    })
    .catch(error => {
        console.error('加载权限列表失败:', error);
    });
}

// 渲染权限列表
function renderPermissions(permissions) {
    const container = document.getElementById('permissions-accordion');
    
    // 按分类分组
    const categories = {};
    permissions.forEach(permission => {
        const category = permission.category || 'other';
        if (!categories[category]) {
            categories[category] = [];
        }
        categories[category].push(permission);
    });
    
    const categoryNames = {
        'core': '核心功能',
        'file': '文件管理',
        'template': '模板管理',
        'task': '任务管理',
        'analytics': '数据分析',
        'settings': '系统设置',
        'user': '用户管理',
        'other': '其他'
    };
    
    container.innerHTML = Object.keys(categories).map((category, index) => `
        <div class="accordion-item">
            <h2 class="accordion-header">
                <button class="accordion-button ${index === 0 ? '' : 'collapsed'}" type="button" data-bs-toggle="collapse" data-bs-target="#category-${category}">
                    <i class="fas fa-folder me-2"></i>
                    ${categoryNames[category] || category}
                    <span class="badge bg-primary ms-2">${categories[category].length}</span>
                </button>
            </h2>
            <div id="category-${category}" class="accordion-collapse collapse ${index === 0 ? 'show' : ''}">
                <div class="accordion-body">
                    <div class="row">
                        ${categories[category].map(permission => `
                            <div class="col-md-6 mb-2">
                                <div class="card card-body p-2">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div class="flex-grow-1">
                                            <h6 class="mb-1">${permission.name}</h6>
                                            <small class="text-muted">${permission.code}</small>
                                            ${permission.description ? `<p class="mb-1 small">${permission.description}</p>` : ''}
                                            <span class="badge bg-secondary">级别 ${permission.level}</span>
                                            ${permission.is_system ? '<span class="badge bg-dark ms-1">系统</span>' : ''}
                                        </div>
                                        <div class="dropdown">
                                            <button class="btn btn-sm btn-outline-secondary" data-bs-toggle="dropdown">
                                                <i class="fas fa-ellipsis-v"></i>
                                            </button>
                                            <ul class="dropdown-menu">
                                                <li><a class="dropdown-item" href="#" onclick="editPermission(${permission.id})"><i class="fas fa-edit me-2"></i>编辑</a></li>
                                                ${!permission.is_system ? '<li><a class="dropdown-item text-danger" href="#" onclick="deletePermission(' + permission.id + ')"><i class="fas fa-trash me-2"></i>删除</a></li>' : ''}
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `).join('')}
                    </div>
                </div>
            </div>
        </div>
    `).join('');
}

// 加载权限矩阵
function loadPermissionMatrix() {
    fetch('/settings/ajax/permission-matrix/')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            renderPermissionMatrix(data.matrix);
        }
    })
    .catch(error => {
        console.error('加载权限矩阵失败:', error);
    });
}

// 渲染权限矩阵
function renderPermissionMatrix(matrix) {
    const table = document.getElementById('permissions-matrix');
    
    if (!matrix.roles || !matrix.permissions) {
        table.innerHTML = '<tr><td class="text-center">暂无数据</td></tr>';
        return;
    }
    
    // 表头
    let html = '<thead><tr><th>权限</th>';
    matrix.roles.forEach(role => {
        html += `<th class="text-center">${role.name}</th>`;
    });
    html += '</tr></thead><tbody>';
    
    // 表体
    matrix.permissions.forEach(permission => {
        html += `<tr><td><strong>${permission.name}</strong><br><small class="text-muted">${permission.code}</small></td>`;
        
        matrix.roles.forEach(role => {
            const hasPermission = matrix.matrix[role.id] && matrix.matrix[role.id].includes(permission.id);
            html += `
                <td class="text-center">
                    <div class="form-check form-switch d-flex justify-content-center">
                        <input class="form-check-input" type="checkbox" ${hasPermission ? 'checked' : ''} 
                               onchange="toggleRolePermission(${role.id}, ${permission.id}, this.checked)">
                    </div>
                </td>
            `;
        });
        
        html += '</tr>';
    });
    
    html += '</tbody>';
    table.innerHTML = html;
}

// 切换角色权限
function toggleRolePermission(roleId, permissionId, hasPermission) {
    fetch('/settings/ajax/role-permission/toggle/', {
        method: 'POST',
        body: JSON.stringify({
            role_id: roleId,
            permission_id: permissionId,
            has_permission: hasPermission
        }),
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('权限更新成功', 'success');
        } else {
            CFS.utils.showNotification(data.message || '权限更新失败', 'error');
            // 恢复复选框状态
            event.target.checked = !hasPermission;
        }
    })
    .catch(error => {
        console.error('更新权限失败:', error);
        CFS.utils.showNotification('权限更新失败', 'error');
        // 恢复复选框状态
        event.target.checked = !hasPermission;
    });
}

// 添加角色
function addRole() {
    currentRoleId = null;
    document.getElementById('roleModalTitle').textContent = '添加角色';
    document.getElementById('role-form').reset();
    
    // 加载权限树
    loadPermissionTree();
    
    const modal = new bootstrap.Modal(document.getElementById('roleModal'));
    modal.show();
}

// 编辑角色
function editRole(roleId) {
    currentRoleId = roleId;
    document.getElementById('roleModalTitle').textContent = '编辑角色';
    
    // 加载角色数据
    fetch(`/settings/ajax/roles/${roleId}/`)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            populateRoleForm(data.role);
            loadPermissionTree(data.role.permissions);
            
            const modal = new bootstrap.Modal(document.getElementById('roleModal'));
            modal.show();
        }
    })
    .catch(error => {
        console.error('加载角色数据失败:', error);
    });
}

// 填充角色表单
function populateRoleForm(role) {
    document.getElementById('role-id').value = role.id;
    document.getElementById('role-name').value = role.name;
    document.getElementById('role-code').value = role.code;
    document.getElementById('role-description').value = role.description || '';
    document.getElementById('role-level').value = role.level;
    document.getElementById('role-status').value = role.status;
    document.getElementById('role-is-default').checked = role.is_default;
    document.getElementById('role-is-system').checked = role.is_system;
}

// 加载权限树
function loadPermissionTree(selectedPermissions = []) {
    const container = document.getElementById('role-permissions-tree');
    
    // 按分类分组权限
    const categories = {};
    allPermissions.forEach(permission => {
        const category = permission.category || 'other';
        if (!categories[category]) {
            categories[category] = [];
        }
        categories[category].push(permission);
    });
    
    const categoryNames = {
        'core': '核心功能',
        'file': '文件管理',
        'template': '模板管理',
        'task': '任务管理',
        'analytics': '数据分析',
        'settings': '系统设置',
        'user': '用户管理',
        'other': '其他'
    };
    
    container.innerHTML = Object.keys(categories).map(category => `
        <div class="mb-3">
            <div class="form-check">
                <input class="form-check-input category-checkbox" type="checkbox" id="category-${category}" 
                       onchange="toggleCategoryPermissions('${category}')">
                <label class="form-check-label fw-bold" for="category-${category}">
                    ${categoryNames[category] || category}
                </label>
            </div>
            <div class="ms-3">
                ${categories[category].map(permission => `
                    <div class="form-check">
                        <input class="form-check-input permission-checkbox" type="checkbox" 
                               id="permission-${permission.id}" value="${permission.id}" 
                               data-category="${category}" 
                               ${selectedPermissions.includes(permission.id) ? 'checked' : ''}
                               onchange="updateCategoryCheckbox('${category}')">
                        <label class="form-check-label" for="permission-${permission.id}">
                            ${permission.name}
                            <small class="text-muted">(${permission.code})</small>
                        </label>
                    </div>
                `).join('')}
            </div>
        </div>
    `).join('');
    
    // 更新分类复选框状态
    Object.keys(categories).forEach(category => {
        updateCategoryCheckbox(category);
    });
}

// 切换分类权限
function toggleCategoryPermissions(category) {
    const categoryCheckbox = document.getElementById(`category-${category}`);
    const permissionCheckboxes = document.querySelectorAll(`input[data-category="${category}"]`);
    
    permissionCheckboxes.forEach(checkbox => {
        checkbox.checked = categoryCheckbox.checked;
    });
}

// 更新分类复选框状态
function updateCategoryCheckbox(category) {
    const categoryCheckbox = document.getElementById(`category-${category}`);
    const permissionCheckboxes = document.querySelectorAll(`input[data-category="${category}"]`);
    const checkedCount = document.querySelectorAll(`input[data-category="${category}"]:checked`).length;
    
    categoryCheckbox.checked = checkedCount === permissionCheckboxes.length && permissionCheckboxes.length > 0;
    categoryCheckbox.indeterminate = checkedCount > 0 && checkedCount < permissionCheckboxes.length;
}

// 全选权限
function selectAllPermissions() {
    document.querySelectorAll('.permission-checkbox').forEach(checkbox => {
        checkbox.checked = true;
    });
    
    document.querySelectorAll('.category-checkbox').forEach(checkbox => {
        checkbox.checked = true;
        checkbox.indeterminate = false;
    });
}

// 清空权限
function clearAllPermissions() {
    document.querySelectorAll('.permission-checkbox').forEach(checkbox => {
        checkbox.checked = false;
    });
    
    document.querySelectorAll('.category-checkbox').forEach(checkbox => {
        checkbox.checked = false;
        checkbox.indeterminate = false;
    });
}

// 保存角色
function saveRole(event) {
    event.preventDefault();
    
    const formData = new FormData(event.target);
    
    // 收集选中的权限
    const selectedPermissions = [];
    document.querySelectorAll('.permission-checkbox:checked').forEach(checkbox => {
        selectedPermissions.push(parseInt(checkbox.value));
    });
    formData.append('permissions', JSON.stringify(selectedPermissions));
    
    const url = currentRoleId ? `/settings/ajax/roles/${currentRoleId}/update/` : '/settings/ajax/roles/create/';
    
    CFS.utils.showLoading(true);
    
    fetch(url, {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification(currentRoleId ? '角色更新成功' : '角色创建成功', 'success');
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('roleModal'));
            modal.hide();
            
            // 重新加载列表
            loadRoles();
            loadPermissionStats();
        } else {
            CFS.utils.showNotification(data.message || '操作失败', 'error');
        }
    })
    .catch(error => {
        console.error('保存角色失败:', error);
        CFS.utils.showNotification('保存角色失败', 'error');
    })
    .finally(() => {
        CFS.utils.showLoading(false);
    });
}

// 查看角色详情
function viewRole(roleId) {
    fetch(`/settings/ajax/roles/${roleId}/detail/`)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            renderRoleDetail(data.role);
            
            const modal = new bootstrap.Modal(document.getElementById('roleDetailModal'));
            modal.show();
        }
    })
    .catch(error => {
        console.error('加载角色详情失败:', error);
    });
}

// 渲染角色详情
function renderRoleDetail(role) {
    const content = document.getElementById('role-detail-content');
    
    content.innerHTML = `
        <div class="row g-3">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0">基本信息</h6>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr><td>角色名称:</td><td>${role.name}</td></tr>
                            <tr><td>角色代码:</td><td><code>${role.code}</code></td></tr>
                            <tr><td>角色级别:</td><td>级别 ${role.level}</td></tr>
                            <tr><td>状态:</td><td><span class="badge bg-${role.status === 'active' ? 'success' : 'secondary'}">${role.status === 'active' ? '启用' : '禁用'}</span></td></tr>
                            <tr><td>创建时间:</td><td>${role.created_at}</td></tr>
                        </table>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0">统计信息</h6>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr><td>用户数量:</td><td>${role.user_count}</td></tr>
                            <tr><td>权限数量:</td><td>${role.permission_count}</td></tr>
                            <tr><td>默认角色:</td><td>${role.is_default ? '<i class="fas fa-check text-success"></i>' : '<i class="fas fa-times text-muted"></i>'}</td></tr>
                            <tr><td>系统角色:</td><td>${role.is_system ? '<i class="fas fa-check text-success"></i>' : '<i class="fas fa-times text-muted"></i>'}</td></tr>
                        </table>
                    </div>
                </div>
            </div>
            ${role.description ? `
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h6 class="mb-0">角色描述</h6>
                        </div>
                        <div class="card-body">
                            <p class="mb-0">${role.description}</p>
                        </div>
                    </div>
                </div>
            ` : ''}
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0">权限列表</h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            ${role.permissions.map(permission => `
                                <div class="col-md-4 mb-2">
                                    <span class="badge bg-primary">${permission.name}</span>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    currentRoleId = role.id;
}

// 从详情页编辑角色
function editRoleFromDetail() {
    // 关闭详情模态框
    const detailModal = bootstrap.Modal.getInstance(document.getElementById('roleDetailModal'));
    detailModal.hide();
    
    // 打开编辑模态框
    setTimeout(() => {
        editRole(currentRoleId);
    }, 300);
}

// 复制角色
function copyRole(roleId) {
    fetch(`/settings/ajax/roles/${roleId}/copy/`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('角色复制成功', 'success');
            loadRoles();
        } else {
            CFS.utils.showNotification(data.message || '角色复制失败', 'error');
        }
    })
    .catch(error => {
        console.error('复制角色失败:', error);
        CFS.utils.showNotification('复制角色失败', 'error');
    });
}

// 删除角色
function deleteRole(roleId) {
    if (!confirm('确定要删除该角色吗？此操作不可逆！')) {
        return;
    }
    
    CFS.utils.showLoading(true);
    
    fetch(`/settings/ajax/roles/${roleId}/delete/`, {
        method: 'DELETE',
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('角色删除成功', 'success');
            loadRoles();
            loadPermissionStats();
        } else {
            CFS.utils.showNotification(data.message || '角色删除失败', 'error');
        }
    })
    .catch(error => {
        console.error('删除角色失败:', error);
        CFS.utils.showNotification('删除角色失败', 'error');
    })
    .finally(() => {
        CFS.utils.showLoading(false);
    });
}

// 添加权限
function addPermission() {
    currentPermissionId = null;
    document.getElementById('permissionModalTitle').textContent = '添加权限';
    document.getElementById('permission-form').reset();
    
    const modal = new bootstrap.Modal(document.getElementById('permissionModal'));
    modal.show();
}

// 编辑权限
function editPermission(permissionId) {
    currentPermissionId = permissionId;
    document.getElementById('permissionModalTitle').textContent = '编辑权限';
    
    // 加载权限数据
    const permission = allPermissions.find(p => p.id === permissionId);
    if (permission) {
        populatePermissionForm(permission);
        
        const modal = new bootstrap.Modal(document.getElementById('permissionModal'));
        modal.show();
    }
}

// 填充权限表单
function populatePermissionForm(permission) {
    document.getElementById('permission-id').value = permission.id;
    document.getElementById('permission-name').value = permission.name;
    document.getElementById('permission-code').value = permission.code;
    document.getElementById('permission-category').value = permission.category;
    document.getElementById('permission-description').value = permission.description || '';
    document.getElementById('permission-level').value = permission.level;
    document.getElementById('permission-is-system').checked = permission.is_system;
}

// 保存权限
function savePermission(event) {
    event.preventDefault();
    
    const formData = new FormData(event.target);
    const url = currentPermissionId ? `/settings/ajax/permissions/${currentPermissionId}/update/` : '/settings/ajax/permissions/create/';
    
    CFS.utils.showLoading(true);
    
    fetch(url, {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification(currentPermissionId ? '权限更新成功' : '权限创建成功', 'success');
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('permissionModal'));
            modal.hide();
            
            // 重新加载列表
            loadPermissions();
            loadPermissionStats();
        } else {
            CFS.utils.showNotification(data.message || '操作失败', 'error');
        }
    })
    .catch(error => {
        console.error('保存权限失败:', error);
        CFS.utils.showNotification('保存权限失败', 'error');
    })
    .finally(() => {
        CFS.utils.showLoading(false);
    });
}

// 删除权限
function deletePermission(permissionId) {
    if (!confirm('确定要删除该权限吗？此操作不可逆！')) {
        return;
    }
    
    CFS.utils.showLoading(true);
    
    fetch(`/settings/ajax/permissions/${permissionId}/delete/`, {
        method: 'DELETE',
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('权限删除成功', 'success');
            loadPermissions();
            loadPermissionStats();
        } else {
            CFS.utils.showNotification(data.message || '权限删除失败', 'error');
        }
    })
    .catch(error => {
        console.error('删除权限失败:', error);
        CFS.utils.showNotification('删除权限失败', 'error');
    })
    .finally(() => {
        CFS.utils.showLoading(false);
    });
}

// 刷新权限矩阵
function refreshMatrix() {
    loadPermissionMatrix();
}

// 导出权限矩阵
function exportMatrix() {
    window.open('/settings/ajax/permission-matrix/export/');
}
</script>
{% endblock %}